//
//  SYJOauthViewController.swift
//  weibo
//
//  Created by 孙英建 on 16/4/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

// https://api.weibo.com/oauth2/authorize?client_id=1600675887&redirect_uri=http://www.baidu.com

class SYJOauthViewController: UIViewController {

    
    // 将控制器的跟视图设置为UIWebView
    override func loadView() {
        view = web
        
        web.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirect_uri)")
        
        let request = NSURLRequest(URL: url!)
        
        web.loadRequest(request)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setViewController()

    }

    // 设置控制器属性
    func setViewController(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoStuff")
    }
    
    // MARK: - 按钮的点击事件
    
    // 取消按钮
    @objc private func cancel(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 自动填充
    @objc private func autoStuff(){
       
        let jsString = "document.getElementById('userId').value='\(userName)';document.getElementById('passwd').value='\(password)'"
        
        web.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 懒加载控件
    
    // 加载webView
    lazy var web: UIWebView = {
        let wb = UIWebView()
        
        return wb
    }()
    
}

extension SYJOauthViewController: UIWebViewDelegate{
    
    // webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    // webView结束接在
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 将要加载url时
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // http://www.baidu.com/?code=17790d16de780b60793c807e77bfe735
        
        // 判断是否request是否有值并且前缀是否为回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(redirect_uri) {
            
            // 截取字符串
            if let query = request.URL?.query {
                
                let code = query.substringFromIndex("code=".endIndex)
               
                // 请求accessToken
                getAccessToken(code)
            }
        }
        return true
    }
    
}


extension SYJOauthViewController{
    
    // MARK: - 请求accessToken
    func getAccessToken(code: String){
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        
        
        NetWorkTools.sharedTools.request(ResquestMethod.POST, urlString: urlString, paramaters: params) { (response, error) -> () in
            
            if error != nil {
                print("请求失败\(error)")
                return
            }
            
            // 成功
            guard let dataDict = response as? [String: AnyObject] else {
                return
            }
        
            let count: SYJAccountModel = SYJAccountModel(dict: dataDict)
          
            self.getUserInfo(count)
        
        }
    }
    
    // MARK: - 请求用户信息
    func getUserInfo(count: SYJAccountModel){

        let url: String = "https://api.weibo.com/2/users/show.json"
        let paramaters: Dictionary = [
            "access_token":count.access_token!,
            "uid":count.uid!
        ]
        
        // 请求用户信息
        NetWorkTools.sharedTools.request(ResquestMethod.GET, urlString: url, paramaters: paramaters) { (response, error) -> () in
            
            if error != nil{
                print("请求失败\(error)")
                return
            }
            
            // 请求成功 判断可选值
            guard let userInfo = response as? [String: AnyObject] else{
                return
            }
            
            count.avatar_large = userInfo["avatar_large"] as? String
            count.screen_name = userInfo["screen_name"] as? String
            
            // 保存用户信息
            SYJUserAccountTools.sharedTools.saveUserAccount(count)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                // 发通知切换控制器
                NSNotificationCenter.defaultCenter().postNotificationName("switchDefaultController", object: nil)
            })
            
        }
  
    }
    

}







